<?php
namespace app\job;

use addons\faqueue\library\QueueApi;
use think\Db;
use think\Log;
use think\queue\Job;

class Job1{

    public function fire(Job $job, $data){

        //....这里执行具体的任务
        //自动发货
        log::write(["msg"=>"发货开始"],"log");
        self::sendGoods($data['out_trade_no'],$data['transaction_id'],$data['openid']);
        log::write(["msg"=>"发货结束"],"log");

        if ($job->attempts() > 3) {
            //通过这个方法可以检查这个任务已经重试了几次了
            log::write(["msg"=>"任务已经超过三次"],"log");
        }


        //如果任务执行成功后 记得删除任务，不然这个任务会重复执行，直到达到最大重试次数后失败后，执行failed方法
        $job->delete();

        return true;

        // 也可以重新发布这个任务
//        $job->release($delay); //$delay为延迟时间

    }
    private function sendGoods($out_trade_no,$transaction_id,$openid){
        $order = Db::table('box_order')->field("user_id,boxfl_name,num,out_trade_no,transaction_id")->where('out_trade_no', $out_trade_no)->find();
        log::write(["msg"=>"发货订单信息","data"=>$order],"log");
        $tmp = $this->getAccessToken();
        $tmptoken = json_decode($tmp);
        $token = $tmptoken->access_token;
        $data['order_key']['order_number_type'] =2;
        $data['order_key']['transaction_id'] = $transaction_id;
        $data['logistics_type'] = 3;
        $data['delivery_mode'] = 1;
        $data['shipping_list'][0]['item_desc'] = $order['boxfl_name'].'数量*'.$order['num'];
        $data['upload_time'] = self::formatTime();
        $data['payer']['openid'] = $openid;
        $url = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=$token";
        log::write(["msg"=>"发货参数","data"=>$data],"log");
        $info = $this->http_request($url, json_encode($data,JSON_UNESCAPED_UNICODE), 'json');
        // 一定要注意转json，否则汇报47001错误
        //$tmpinfo = json_decode($info);
        log::write(["msg"=>"发货结果","data"=>$info],"log");
        return true;
    }
    /*获取access_token,不能用于获取用户信息的token*/
    public  function getAccessToken()
    {
        $s = Db::table('box_setting')->where('id', 1)->find();
        $appid = $s['mpappid'];
        $secret = $s['mpappkey'];
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret . "";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }
    //图片合法性验证
    public function http_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, TRUE);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json'
            ));
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        $output = curl_exec($curl);
        curl_close($curl);

        return $output;
    }
    private function formatTime(){
        $dateTime = new \DateTime("now",new \DateTimeZone("Asia/Shanghai"));
        // 获取时区偏移量并转换为格式化字符串
        $timeZoneOffset = $dateTime->format("P");
        // 格式化日期时间
        $formattedDateTime = $dateTime->format("Y-m-d\TH:i:s.u") . $timeZoneOffset;
        return $formattedDateTime;
    }

    public function failed($data){
        log::write(["msg"=>"失败原因","data"=>$data],"log");
        // ...任务达到最大重试次数后，失败了
    }

}